import matplotlib.pyplot as plt
import cv2
import os
import numpy as np
import csv

"""
A module for helping function
"""


def show_img(img, title):
    plt.imshow(img, 'gray')
    plt.title(title)
    plt.show()


# this function is for read image,the input is directory name
def read_directory(path):
    img_list = []
    # this loop is for read each image in this folder, directory_name is the folder name with images.
    for filename in sorted(os.listdir(path)):
        # print(filename) #just for test
        # img is used to store the image data
        img = cv2.imread(path + "/" + filename)
        img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        img_list.append(img_gray)
    print(f'{path} has {len(img_list)} images')

    return img_list


def save_images_to_disk(images, path):
    count = 1
    for img in images:
        cv2.imwrite(f'{path}/{count}.tif', img)
        count = count + 1


color_list = []

# use this function for generate different color for different cells
def color_generators(num):
    for i in range(0, num - len(color_list)):
        bgr = np.random.randint(0, 255, 3, dtype=np.int32)
        color = (int(bgr[0]), int(bgr[1]), int(bgr[2]))
        while color in color_list:
            bgr = np.random.randint(0, 255, 3, dtype=np.int32)
            color = (int(bgr[0]), int(bgr[1]), int(bgr[2]))
        color_list.append(color)
    return color_list


def get_color_list(num):
    if len(color_list) >= num:
        return color_list[:num]
    else:
        color_generators(num)
        return color_list[:num]


def saveCvs(data):
    # Windows default is gbk

    # headers = ['Cells', 'Mitoses', 'Displacement', 'Size']
    file_obj = open('data.csv', 'a', encoding="gbk", newline='')
    writer = csv.writer(file_obj)
    writer.writerow(data)

    file_obj.close()
    print('finished!')


# This function is used for display information we need to show on the image
def draw_img_info(img, cell_list):
    cell_num = len(cell_list)
    all_area = 0
    mitoses_num = 0
    all_path = 0
    for cell in cell_list:
        all_area += cell.area
        all_path += cell.path_length
        if cell.is_splitting > 0:
            mitoses_num += 1

    text = "Number of Cells Detected: {}".format(cell_num)
    cv2.putText(img, text, (20, 20), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255), 1)

    text = "Number of Mitoses Detected: {}".format(mitoses_num)
    cv2.putText(img, text, (20, 40), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255), 1)

    text = "The Average Displacement (in pixels) of all the cells: {}".format(round(all_path / cell_num, 2))
    cv2.putText(img, text, (20, 80), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255), 1)

    text = "The Average Size (in pixels) of all the cells: {}".format(round(all_area / cell_num, 2))
    cv2.putText(img, text, (20, 60), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255), 1)

    # saveCvs([cell_num, mitoses_num, round(all_path / cell_num, 2), round(all_area / cell_num, 2)])
    return img
